route.ts 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. import { getServerSideConfig } from "@/app/config/server";
  2. import {
  3. Alibaba,
  4. ALIBABA_BASE_URL,
  5. ApiPath,
  6. ModelProvider,
  7. ServiceProvider,
  8. } from "@/app/constant";
  9. import { prettyObject } from "@/app/utils/format";
  10. import { NextRequest, NextResponse } from "next/server";
  11. import { auth } from "@/app/api/auth";
  12. import { isModelAvailableInServer } from "@/app/utils/model";
  13. import type { RequestPayload } from "@/app/client/platforms/openai";
  14. const serverConfig = getServerSideConfig();
  15. async function handle(
  16. req: NextRequest,
  17. { params }: { params: { path: string[] } },
  18. ) {
  19. console.log("[Alibaba Route] params ", params);
  20. if (req.method === "OPTIONS") {
  21. return NextResponse.json({ body: "OK" }, { status: 200 });
  22. }
  23. const authResult = auth(req, ModelProvider.Qwen);
  24. if (authResult.error) {
  25. return NextResponse.json(authResult, {
  26. status: 401,
  27. });
  28. }
  29. try {
  30. const response = await request(req);
  31. return response;
  32. } catch (e) {
  33. console.error("[Alibaba] ", e);
  34. return NextResponse.json(prettyObject(e));
  35. }
  36. }
  37. export const GET = handle;
  38. export const POST = handle;
  39. export const runtime = "edge";
  40. export const preferredRegion = [
  41. "arn1",
  42. "bom1",
  43. "cdg1",
  44. "cle1",
  45. "cpt1",
  46. "dub1",
  47. "fra1",
  48. "gru1",
  49. "hnd1",
  50. "iad1",
  51. "icn1",
  52. "kix1",
  53. "lhr1",
  54. "pdx1",
  55. "sfo1",
  56. "sin1",
  57. "syd1",
  58. ];
  59. async function request(req: NextRequest) {
  60. const controller = new AbortController();
  61. // alibaba use base url or just remove the path
  62. let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Alibaba, "");
  63. let baseUrl = serverConfig.alibabaUrl || ALIBABA_BASE_URL;
  64. if (!baseUrl.startsWith("http")) {
  65. baseUrl = `https://${baseUrl}`;
  66. }
  67. if (baseUrl.endsWith("/")) {
  68. baseUrl = baseUrl.slice(0, -1);
  69. }
  70. console.log("[Proxy] ", path);
  71. console.log("[Base Url]", baseUrl);
  72. const timeoutId = setTimeout(
  73. () => {
  74. controller.abort();
  75. },
  76. 10 * 60 * 1000,
  77. );
  78. const fetchUrl = `${baseUrl}${path}`;
  79. const fetchOptions: RequestInit = {
  80. headers: {
  81. "Content-Type": "application/json",
  82. Authorization: req.headers.get("Authorization") ?? "",
  83. "X-DashScope-SSE": req.headers.get("X-DashScope-SSE") ?? "disable",
  84. },
  85. method: req.method,
  86. body: req.body,
  87. redirect: "manual",
  88. // @ts-ignore
  89. duplex: "half",
  90. signal: controller.signal,
  91. };
  92. // #1815 try to refuse some request to some models
  93. if (serverConfig.customModels && req.body) {
  94. try {
  95. const clonedBody = await req.text();
  96. fetchOptions.body = clonedBody;
  97. const jsonBody = JSON.parse(clonedBody) as { model?: string };
  98. // not undefined and is false
  99. if (
  100. isModelAvailableInServer(
  101. serverConfig.customModels,
  102. jsonBody?.model as string,
  103. ServiceProvider.Alibaba as string,
  104. )
  105. ) {
  106. return NextResponse.json(
  107. {
  108. error: true,
  109. message: `you are not allowed to use ${jsonBody?.model} model`,
  110. },
  111. {
  112. status: 403,
  113. },
  114. );
  115. }
  116. } catch (e) {
  117. console.error(`[Alibaba] filter`, e);
  118. }
  119. }
  120. try {
  121. const res = await fetch(fetchUrl, fetchOptions);
  122. // to prevent browser prompt for credentials
  123. const newHeaders = new Headers(res.headers);
  124. newHeaders.delete("www-authenticate");
  125. // to disable nginx buffering
  126. newHeaders.set("X-Accel-Buffering", "no");
  127. return new Response(res.body, {
  128. status: res.status,
  129. statusText: res.statusText,
  130. headers: newHeaders,
  131. });
  132. } finally {
  133. clearTimeout(timeoutId);
  134. }
  135. }